package com.password.services;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

import com.password.entity.User;
import com.password.util.DesUtil;
import com.password.util.FileEncrptUtil;
import com.password.util.SystemConfig;

/**
 * 用于文件的加密
 * @author yzh
 * @date 2020年5月28日
 *
 */
public class FileSecretService {

	private final UserService userServices = UserService.getUserServices();

	private FileSecretService() {
	}

	private static class FileSecretServiceBuilder {
		private static FileSecretService fileSecretService = new FileSecretService();
	}

	public static FileSecretService getFileSecretService() {
		return FileSecretServiceBuilder.fileSecretService;
	}

	/**
	 * 加密文件
	 * @author yzh
	 * @date 2020年5月27日
	 * 
	 * @param user     用户名
	 * @param password 密码
	 * @param text     加密的文档
	 * @return 加密的文本内容
	 * @throws Exception
	 */
	public void encodeFile(String user, String password, File inputFile, File outFile) throws Exception {
		User userD = userServices.getUser(user, password);
		encodeFile(userD, inputFile, outFile);
	}

	public void encodeFile(User user, File inputFile, File outFile) throws Exception {
		FileEncrptUtil.fileEncrpt(user.getRsaKey(), user.getFixedDexKey(), new FileInputStream(inputFile),
				new FileOutputStream(outFile));
	}

	/**
	 * 解密文件
	 * @author yzh
	 * @date 2020年5月28日
	 *  
	 * @param user
	 * @param password
	 * @param inputFile
	 * @param outFile
	 * @throws Exception
	 */
	public void decodeFile(String user, String password, File inputFile, File outFile) throws Exception {
		User userD = userServices.getUser(user, password);
		decodeFile(userD, inputFile, outFile);
	}

	public void decodeFile(User user, File inputFile, File outFile) throws Exception {
		File file = new File(SystemConfig.getContextPath(), SystemConfig.getUserPrivateKeyFileName(user.getUserName()));
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));) {
			String privateKey = reader.readLine();
			FileEncrptUtil.fileDecrypt(DesUtil.decrypt(privateKey, user.getFixedDexKey(), "UTF-8"),
					new FileInputStream(inputFile), new FileOutputStream(outFile));
		}

	}

}
